#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <string>

// 全局的条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// 全局锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

static const int start = 1, end = 100;
int cur = 1;
void *my_print(void *args)
{
    std::string name = (char *)args;
    // int count = 10;
    // while(count--)
    // {
    //     sleep(1);
    //     std::cout<<name.c_str()<<std::endl;
    // }

    while (cur <= 100)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);

        std::cout << name.c_str() << " " << cur << std::endl;
        cur++;

        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    // 创建两个线程
    pthread_t th1, th2;
    pthread_create(&th1, nullptr, my_print, (void *)"th1");
    pthread_create(&th2, nullptr, my_print, (void *)"th2");

    sleep(1);
    // 主线程等待
    while (true)
    {
        pthread_cond_signal(&cond);
        usleep(10000);
    }

    pthread_join(th1, nullptr);
    pthread_join(th2, nullptr);

    return 0;
}